package com.zhongxi.guoyuan.base;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class BaseFragment extends Fragment {

    protected TextView tvTitle;
    protected ImageView ivBack;
    protected Context context;

    protected int pageNum = 1;
    private ProgressDialog progressDialog;

    protected Disposable disposable;
    private String url;

    @Override
    public void onDestroyView() {
        unsubscribe();
        super.onDestroyView();
    }

    public void unsubscribe() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    class StringCallback extends com.zhy.http.okhttp.callback.StringCallback {

        @Override
        public void onError(Call call, Exception e, int id) {
            try {
                System.out.println("e.getMessage()==" + e.getMessage());
                if (e.getMessage().equals("timeout")) {
                    showShortToast(url + "联网超时,请重试");
                } else {
                    showShortToast(url + "联网失败");
                }
            } finally {
                hideProgressDialog();
            }
        }

        @Override
        public void onResponse(String response, int id) {
            try {
                JSONObject obj = new JSONObject(response);
                int code = obj.getInt("code");
                if (code == 1) {
                    processSuccessResult(response);
                } else if (code == 7002) {
                    processOldUser(response);
                } else if (code == 2816) {
                    logoutDialog();
                } else {
                    ProcessFailResult(response);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                hideProgressDialog();
            }
        }
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(getActivity()).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            startAct(MainHomeActivity.class);
        }
    }

    private void processFailRequest(String message) {
    }

    protected void processOldUser(String response) {
    }

    /**
     * 请求失败
     */
    protected void ProcessFailResult(String response) {
    }

    /**
     * 请求成功
     */
    protected void processSuccessResult(String response) {
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        initView();
        initData();
        initEvent();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    protected void initTitle() {
        tvTitle = (TextView) getView().findViewById(R.id.tvTitle);
        ivBack = (ImageView) getView().findViewById(R.id.ivBack);
    }

    protected void initEvent() {
    }

    protected void initData() {
    }

    protected void initView() {
    }

    /**
     * 获取网络请求 map -- 传递参数
     *
     * @param
     * @param getStr
     */
    public void getServer(String url, Map<String, String> map, String getStr, boolean isUser, StringCallback callback, String type) {
        this.url = url;
        try {
            if (map == null) {
                map = new HashMap<>();
            }
            if (callback == null) {
                callback = new StringCallback();
            }
            String baseUrl = url + "/" + MyApplication.getInstance().getUrl() + "?params=" + MyApplication.getInstance().getCheck(isUser);
            if ("get".equals(type)) {
                System.out.println("baseUrl+getStr==" + baseUrl + getStr);
                getHttpUtils(baseUrl + getStr, callback);
            } else {
                System.out.println("baseUrl+post==" + baseUrl + getStr);
                postHttpUtils(baseUrl + getStr, callback, map);
            }
            if (CommonTool.isFirstScroll())
            showProgressDialog(type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getHttpUtils(String url, StringCallback callback) {
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(callback);
    }

    private void postHttpUtils(String url, StringCallback callback, Map<String, String> map) {
        OkHttpUtils
                .post()
                .url(url)
                .params(map)
                .build()
                .execute(callback);
    }

    /**
     * 展示提交或者加载数据的进度框
     *
     * @param method
     */
    private void showProgressDialog(String method) {
        if (progressDialog == null)
            progressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_HOLO_LIGHT);
        progressDialog.setCancelable(true);
        String progressDialogMessage = "";
        if (!progressDialog.isShowing()) {
            if (method.equals("get"))
                progressDialogMessage = getResources().getString(R.string.get);
            else if (method.equals("upload"))
                progressDialogMessage = getResources().getString(R.string.upload);
            else
                progressDialogMessage = "正在请求数据……";
            progressDialog.setMessage(progressDialogMessage);
            progressDialog.show();
        }
    }

    /**
     * 隐藏对话框
     */
    private void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog.cancel();
        }
    }

    public void startAct(Class clazz) {
        Intent intent = new Intent(context, clazz);
        context.startActivity(intent);
    }

    public void showShortToast(String message) {
        Toast.makeText(UiUtils.getContext(), message, Toast.LENGTH_SHORT).show();
    }


}
